package xiaozhi.modules.sys.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import xiaozhi.common.page.PageData;
import xiaozhi.common.service.impl.BaseServiceImpl;
import xiaozhi.common.utils.ConvertUtils;
import xiaozhi.modules.security.oauth2.TokenGenerator;
import xiaozhi.modules.security.user.SecurityUser;
import xiaozhi.modules.sys.dao.SysApiKeyDao;
import xiaozhi.modules.sys.dto.SysApiKeyDTO;
import xiaozhi.modules.sys.entity.SysApiKeyEntity;
import xiaozhi.modules.sys.service.SysApiKeyService;

/**
 * API密钥管理
 */
@Service
@AllArgsConstructor
public class SysApiKeyServiceImpl extends BaseServiceImpl<SysApiKeyDao, SysApiKeyEntity> implements SysApiKeyService {

    @Override
    public PageData<SysApiKeyDTO> page(Map<String, Object> params) {
        // 设置当前用户ID作为查询条件
        params.put("userId", SecurityUser.getUserId());

        IPage<SysApiKeyEntity> page = baseDao.selectPage(
                getPage(params, "create_date", false),
                getWrapper(params)
        );
        
        return getPageData(page, SysApiKeyDTO.class);
    }

    @Override
    public List<SysApiKeyDTO> list(Map<String, Object> params) {
        // 设置当前用户ID作为查询条件
        params.put("userId", SecurityUser.getUserId());

        List<SysApiKeyEntity> entityList = baseDao.selectList(getWrapper(params));
        return ConvertUtils.sourceToTarget(entityList, SysApiKeyDTO.class);
    }

    @Override
    public SysApiKeyDTO get(Long id) {
        SysApiKeyEntity entity = baseDao.selectById(id);
        return ConvertUtils.sourceToTarget(entity, SysApiKeyDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysApiKeyDTO dto) {
        SysApiKeyEntity entity = ConvertUtils.sourceToTarget(dto, SysApiKeyEntity.class);
        
        // 生成API密钥
        entity.setApiKey(generateApiKey());
        
        // 设置用户ID
        entity.setUserId(SecurityUser.getUserId());
        
        // 设置状态为正常
        entity.setStatus(1);
        
        baseDao.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysApiKeyDTO dto) {
        SysApiKeyEntity entity = ConvertUtils.sourceToTarget(dto, SysApiKeyEntity.class);
        baseDao.updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String[] ids) {
        baseDao.deleteBatchIds(Arrays.asList(ids));
    }
    
    @Override
    public SysApiKeyEntity getByApiKey(String apiKey) {
        return baseDao.selectOne(new QueryWrapper<SysApiKeyEntity>()
                .eq("api_key", apiKey));
    }
    
    @Override
    public String generateApiKey() {
        return TokenGenerator.generateValue();
    }
    
    /**
     * 获取查询条件包装器
     */
    private QueryWrapper<SysApiKeyEntity> getWrapper(Map<String, Object> params) {
        QueryWrapper<SysApiKeyEntity> wrapper = new QueryWrapper<>();
        
        String keyName = (String) params.get("keyName");
        Long userId = (Long) params.get("userId");
        
        if (keyName != null && !keyName.trim().isEmpty()) {
            wrapper.like("key_name", keyName);
        }
        
        if (userId != null) {
            wrapper.eq("user_id", userId);
        }
        
        return wrapper;
    }
}